package com.smart.config.core;

import com.smart.config.ConfigProperties;
import com.smart.config.constant.RedisConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @Author xiaoqiang
 * @Version ConfigChangeListener.java, v 0.1 2025年03月18日 11:57 xiaoqiang
 * @Description: TODO
 */
public class ConfigChangeListener implements MessageListener {


    private RedisTemplate<String, String> redisTemplate;

    private ConfigProperties configProperties;

    private ConfigManager configManager;

    private static MessageListener messageListener;


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String publishMessage = new String(message.getBody());

        updateConfigInTransaction(publishMessage);
    }

    public ConfigChangeListener(RedisTemplate<String, String> redisTemplate, ConfigProperties configProperties, ConfigManager configManager) {
        this.redisTemplate = redisTemplate;
        this.configProperties = configProperties;
        this.configManager = configManager;
    }

    public void init() {

        String chanel = RedisConstant.buildRedisChannelName(configProperties.getAppName());//RedisConstant.REDIS_CHANNEL_PREFIX + configProperties.getAppName();

        redisTemplate.getConnectionFactory().getConnection().subscribe(
                this,
                chanel.getBytes()
        );

    }


    private void updateConfigInTransaction(String publishMessage) {

        String[] splitKey = RedisConstant.splitPubMessage(publishMessage);
        String key = splitKey[0];
        Long version = Long.parseLong(splitKey[1]);
        // 事务处理，更新配置到本地缓存
        // 1. 从redis中获取配置
        // 2. 解析配置
        // 3. 更新本地缓存    
        String value = redisTemplate.opsForValue().get(key);

        if (StringUtils.isBlank(value)) {
            return;
        }
        configManager.notifyListener(key, version, value);

    }

}